package com.buaa.singlethreadfileload.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.buaa.singlethreadfileload.bean.ThreadInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据访问接口的实现
 * Created by Administrator on 2016/5/15.
 */
public class ThreadDAOImpl implements ThreadDAO {
    private DBHelper mHelper;

    public ThreadDAOImpl(Context context) {
       mHelper=new DBHelper(context);
    }
    //将线程信息存进数据库
    @Override
    public void insertThread(ThreadInfo threadInfo) {
        SQLiteDatabase db=mHelper.getWritableDatabase();
        db.execSQL("insert into thread_info(thread_id,url,start,end,finished) values(?,?,?,?,?)",new Object[]{threadInfo.getId(),threadInfo.getUrl(),threadInfo.getStart(),threadInfo.getEnd(),threadInfo.getFinished()});
        db.close();
    }

    //根据线程的url和线程的id删除对应的线程
    @Override
    public void deleteThread(String url, int thread_id) {
        SQLiteDatabase db=mHelper.getWritableDatabase();
        db.execSQL("delete from thread_info where url=? and thread_id=?",new Object[]{url,thread_id});
        db.close();

    }

    //根据线程的URL和线程id更新线程状态
    @Override
    public void updateThread(String url, int thread_id, int finished) {
        SQLiteDatabase db=mHelper.getWritableDatabase();
        db.execSQL("update thread_info set finished=? where url=? and thread_id=?",new Object[]{finished,url,thread_id});
        db.close();
    }

    //根据线程URL查询相应的线程信息
    @Override
    public List<ThreadInfo> getThreads(String url) {
        List<ThreadInfo> list=new ArrayList<>();
        SQLiteDatabase db=mHelper.getReadableDatabase();
        Cursor cursor=db.rawQuery("select * from thread_info where url=?",new String[]{url});
        while (cursor.moveToNext()){
            ThreadInfo threadInfo=new ThreadInfo();
            threadInfo.setId(cursor.getInt(cursor.getColumnIndex("thread_id")));
            threadInfo.setUrl(cursor.getString(cursor.getColumnIndex("url")));
            threadInfo.setStart(cursor.getInt(cursor.getColumnIndex("start")));
            threadInfo.setEnd(cursor.getInt(cursor.getColumnIndex("end")));
            threadInfo.setFinished(cursor.getInt(cursor.getColumnIndex("finished")));
            list.add(threadInfo);
        }
        cursor.close();
        db.close();
        return list;
    }

    //根据URL和线程id判断相应的线程是否存在
    @Override
    public boolean isExists(String url, int thread_id) {
       SQLiteDatabase db=mHelper.getReadableDatabase();
        Cursor cursor=db.rawQuery("select * from thread_info where url=? and thread_id=?",new String[]{url,thread_id+""});
        boolean exists=cursor.moveToNext();
        cursor.close();
        db.close();
        return exists;
    }
}
